<template>
  <div class="user-list-container">
    <a-card :bordered="false" class="search-card">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="用户姓名">
          <a-input v-model:value="searchForm.username" placeholder="请输入用户姓名" />
        </a-form-item>
        <a-form-item label="性别">
          <a-select v-model:value="searchForm.gender" placeholder="请选择性别" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="1">男</a-select-option>
            <a-select-option value="2">女</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="searchForm.userStatus" placeholder="请选择状态" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">正常</a-select-option>
            <a-select-option value="1">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
          <a-button type="primary" style="margin-left: 8px" @click="showDrawer" v-if="hasPermission('system::user::create')">新增</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    
    <div class="divider" style="background: #f5f5f5; height: 16px;"></div>
    
    <a-card :bordered="false" class="table-card">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="false"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar :src="record.imageUrl || ''" size="small">
              <template #default >{{ record.realName?.charAt(0) }}</template>
            </a-avatar>
          </template>
          <template v-if="column.key === 'gender'">
            {{ record.gender === 1 ? '男' : '女' }}
          </template>
          <template v-else-if="column.key === 'userStatus'">
            <a-switch 
              :checked="record.userStatus === 0" 
              @change="(checked) => handleStatusChange(record.id, checked)"
              :loading="record.id === statusLoadingId"
              checked-children="启用" 
              un-checked-children="禁用"
            />
          </template>
         <template v-else-if="column.key === 'action'">
            <a-space>
              <a-tooltip title="修改">
                <a-button type="link" size="small" @click="handleEdit(record)">
                  <edit-outlined />
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    <div class="pagination-container">
      <a-pagination
        v-model:current="pagination.current"
        v-model:pageSize="pagination.pageSize"
        :total="pagination.total"
        show-size-changer
        @change="handleTableChange"
      />
    </div>
    <a-drawer
      title="新增用户"
      :width="720"
      :visible="drawerVisible"
      :body-style="{ paddingBottom: '80px' }"
      @close="() => drawerVisible = false"
    >
    <a-divider orientation="left">用户信息</a-divider>
    <a-form label-width="120px" :model="formState" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
      <!-- 用户信息-->
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="姓名" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }" required>
            <a-input v-model:value="formState.realName" placeholder="请输入姓名" allow-clear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="手机" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }" required>
            <a-input v-model:value="formState.phone" placeholder="请输入手机号" allow-clear/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="邮箱" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }" required>
            <a-input v-model:value="formState.email" placeholder="请输入邮箱" allow-clear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="证件号" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
            <a-input v-model:value="formState.idCard" placeholder="请输入证件号" allow-clear/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="联系地址">
            <a-input v-model="formState.address" placeholder="请输入联系地址" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注">
            <a-input v-model="formState.remark" type="textarea" placeholder="请输入备注" clearable/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="性别" required>
            <a-select v-model:value="formState.gender" placeholder="请选择性别" allow-clear>
              <a-select-option :value="0">女性</a-select-option>
              <a-select-option :value="1">男性</a-select-option>
              <a-select-option :value="2">未知</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="出生日期">
            <a-date-picker 
              v-model:value="formState.birthday" 
              placeholder="请选择出生日期" 
              allow-clear
              :value-format="'YYYY-MM-DD'"
              :disabled-date="current => current && current > dayjs().endOf('day')"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="省份">
            <a-input v-model:value="formState.provinceName" placeholder="请选择省份" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="城市">
            <a-input v-model:value="formState.cityName" placeholder="请选择城市" clearable/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="所属机构">
            <a-input v-model:value="formState.orgId" placeholder="请选择机构" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属部门">
            <a-input v-model:value="formState.deptId" placeholder="请输入部门" clearable/>
          </a-form-item>
        </a-col>
      </a-row>
      <!--        账号信息-->
      <a-divider orientation="left">账号信息</a-divider>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="系统账号" required>
            <a-input v-model:value="formState.account" placeholder="请输入系统账号" clearable :disabled="dialogDisable"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="用户账号状态" required>
            <a-select v-model:value="formState.userStatus" placeholder="请选择账号状态" clearable>
              <a-select-option :value="0">启用</a-select-option>
              <a-select-option :value="1">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item name="password" label="登录密码" v-if="!formState.id">
            <a-input v-model:value="formState.password" type="password" placeholder="请输入密码" show-password>
              <template #prefix>
                <a-icon>
                  <lock/>
                </a-icon>
              </template>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item name="confirmPassword" label="确认密码" v-if="!formState.id">
            <a-input v-model:value="formState.confirmPassword" type="password" placeholder="请确认密码" show-password>
              <template #prefix>
                <a-icon>
                  <lock/>
                </a-icon>
              </template>
            </a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="用户账号类型" required>
            <a-select v-model:value="formState.accountType" placeholder="请选择账号类型" clearable  :disabled="dialogDisable">
              <a-select-option value="01">管理员账户</a-select-option>
              <a-select-option value="02">普通用户账户</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="账号注册来源" required>
            <a-select v-model:value="formState.sourceCode" placeholder="请选择账号类型" clearable  :disabled="dialogDisable">
              <a-select-option value="01">管理注册</a-select-option>
              <a-select-option value="02">系统注册</a-select-option>
              <a-select-option value="03">用户注册</a-select-option>
              <a-select-option value="04">三方注册</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="账号角色">
            <a-select v-model:value="formState.roleIds" mode="multiple" collapse-tags collapse-tags-tooltip placeholder="请选择账号角色" style="width: 240px">
              <a-select-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>

          </a-form-item>
        </a-col>
      </a-row>
      <!--        扩展属性-->
      <a-divider orientation="left">扩展属性</a-divider>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="职工编号">
            <a-input v-model:value="formState.employeeNo" placeholder="请输入职工编号" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否三方人员" required>
            <a-select v-model:value="formState.thirdPartyFlag" default-first-option placeholder="请选择是否为三方人员"
                       clearable>
              <a-select-option :value="0">否</a-select-option>
              <a-select-option :value="1">是</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="三方人员ID">
            <a-input v-model:value="formState.thirdPartyId" placeholder="请输入部门" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="三方人员机构">
            <a-input v-model:value="formState.thirdPartyOrg" placeholder="请输入部门" clearable/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="灰度标识" required>
            <a-select v-model:value="formState.grayFlag" default-first-option placeholder="请选择是否为灰度人员"
                       clearable>
              <a-select-option :value="0">否</a-select-option>
              <a-select-option :value="1">是</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div :style="{
      position: 'absolute',
      right: 0,
      bottom: 0,
      width: '100%',
      borderTop: '1px solid #e9e9e9',
      padding: '10px 16px',
      background: '#fff',
      textAlign: 'right',
      zIndex: 1,
    }">
      <a-button style="margin-right: 8px" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleSubmit">确认</a-button>
    </div>
    </a-drawer>

    <a-drawer
    title="编辑用户"
    :width="720"
    :visible="editDrawerVisible"
    :body-style="{ paddingBottom: '80px' }"
    @close="() => editDrawerVisible = false"
    >
    <a-divider orientation="left">用户信息</a-divider>
    <a-form label-width="120px" :model="formState" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
      <!-- 用户信息-->
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="姓名" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }" required>
            <a-input v-model:value="formState.realName" placeholder="请输入姓名" allow-clear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="手机" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }" required>
            <a-input v-model:value="formState.phone" placeholder="请输入手机号" disabled allow-clear/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="邮箱" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }" required>
            <a-input v-model:value="formState.email" placeholder="请输入邮箱" allow-clear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="证件号" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
            <a-input v-model:value="formState.idCard" placeholder="请输入证件号" allow-clear/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="联系地址">
            <a-input v-model="formState.address" placeholder="请输入联系地址" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注">
            <a-input v-model="formState.remark" type="textarea" placeholder="请输入备注" clearable/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="性别" required>
            <a-select v-model:value="formState.gender" placeholder="请选择性别" allow-clear>
              <a-select-option :value="0">女性</a-select-option>
              <a-select-option :value="1">男性</a-select-option>
              <a-select-option :value="2">未知</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="出生日期">
            <a-date-picker 
              v-model:value="formState.birthday" 
              placeholder="请选择出生日期" 
              allow-clear
              :value-format="'YYYY-MM-DD'"
              :disabled-date="current => current && current > dayjs().endOf('day')"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="省份">
            <a-input v-model:value="formState.provinceName" placeholder="请选择省份" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="城市">
            <a-input v-model:value="formState.cityName" placeholder="请选择城市" clearable/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="所属机构">
            <a-input v-model:value="formState.orgId" placeholder="请选择机构" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="所属部门">
            <a-input v-model:value="formState.deptId" placeholder="请输入部门" clearable/>
          </a-form-item>
        </a-col>
      </a-row>
      <!--        账号信息-->
      <a-divider orientation="left">账号信息</a-divider>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="系统账号" required>
            <a-input v-model:value="formState.account" placeholder="请输入系统账号" clearable disabled/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="用户账号状态" required>
            <a-select v-model:value="formState.userStatus" placeholder="请选择账号状态" clearable>
              <a-select-option :value="0">启用</a-select-option>
              <a-select-option :value="1">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item name="password" label="登录密码" v-if="!formState.id">
            <a-input v-model:value="formState.password" type="password" placeholder="请输入密码" disabled show-password>
              <template #prefix>
                <a-icon>
                  <lock/>
                </a-icon>
              </template>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item name="confirmPassword" label="确认密码" v-if="!formState.id && hasPermission('system::user::update')">
            <a-input v-model:value="formState.confirmPassword" type="password" placeholder="请确认密码" disabled show-password>
              <template #prefix>
                <a-icon>
                  <lock/>
                </a-icon>
              </template>
            </a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="用户账号类型" required>
            <a-select v-model:value="formState.accountType" placeholder="请选择账号类型" clearable  disabled>
              <a-select-option value="01">管理员账户</a-select-option>
              <a-select-option value="02">普通用户账户</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="账号注册来源" required>
            <a-select v-model:value="formState.sourceCode" placeholder="请选择账号类型" clearable  disabled>
              <a-select-option value="01">管理注册</a-select-option>
              <a-select-option value="02">系统注册</a-select-option>
              <a-select-option value="03">用户注册</a-select-option>
              <a-select-option value="04">三方注册</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="账号角色">
            <a-select v-model:value="formState.roleIds" mode="multiple" collapse-tags collapse-tags-tooltip placeholder="请选择账号角色" style="width: 240px">
              <a-select-option
                  v-for="item in roleList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>

          </a-form-item>
        </a-col>
      </a-row>
      <!--        扩展属性-->
      <a-divider orientation="left">扩展属性</a-divider>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="职工编号">
            <a-input v-model:value="formState.employeeNo" placeholder="请输入职工编号" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否三方人员" required>
            <a-select v-model:value="formState.thirdPartyFlag" disabled default-first-option placeholder="请选择是否为三方人员"
                      clearable>
              <a-select-option :value="0">否</a-select-option>
              <a-select-option :value="1">是</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="三方人员ID">
            <a-input v-model:value="formState.thirdPartyId" disabled placeholder="请输入部门" clearable/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="三方人员机构">
            <a-input v-model:value="formState.thirdPartyOrg" disabled placeholder="请输入部门" clearable/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="灰度标识" required>
            <a-select v-model:value="formState.grayFlag" default-first-option placeholder="请选择是否为灰度人员"
                      clearable>
              <a-select-option value="0">否</a-select-option>
              <a-select-option value="1">是</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div :style="{
      position: 'absolute',
      right: 0,
      bottom: 0,
      width: '100%',
      borderTop: '1px solid #e9e9e9',
      padding: '10px 16px',
      background: '#fff',
      textAlign: 'right',
      zIndex: 1,
    }">
      <a-button style="margin-right: 8px" @click="handleEditCancel">取消</a-button>
      <a-button type="primary" v-if="hasPermission('system::user::update')" @click="handleEditSubmit">确认</a-button>
    </div>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { hasPermission } from '@/utils/permission';
import { getUsers, createUser, updateUserStatus, searchSysUserInfoById, updateSysUserInfo } from '@/api/system/user';
import { selectRoleList } from '@/api/system/role';
import { message, Modal } from 'ant-design-vue';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';

const columns = [
  {
    title: '用户ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
    width: 80,
  },
  {
    title: '用户姓名',
    dataIndex: 'realName',
    key: 'realName',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '邮箱',
    dataIndex: 'userEmail',
    key: 'userEmail',
  },
  {
    title: '省份/城市',
    key: 'location',
    customRender: ({ record }) => `${record.province || ''}/${record.city || ''}`,
  },
  {
    title: '性别',
    key: 'gender',
  },
  {
    title: '注册时间',
    dataIndex: 'registerTime',
    key: 'registerTime',
    customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
  },
  {
    title: '状态',
    key: 'userStatus',
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
  },
];

const searchForm = reactive({
  username: '',
  gender: '',
  userStatus: '',
});

const drawerVisible = ref(false);
const editDrawerVisible = ref(false);

const formState = ref({
  id:null,
  realName: null,
  email: null,
  phone: null,
  password: null,
  confirmPassword: null,
  gender: 1,
  birthday: null,
  province: null,
  city: null,
  imageUrl: null,
  idCard: null,
  provinceName: null,
  cityName: null,
  address: null,
  remark: null,
  orgId: null,
  deptId: null,
  account: null,
  userStatus: 0,
  roleIds: [],
  accountType: '02',
  loginType: null,
  sourceCode: '01',
  grayFlag: 0,
  employeeNo: null,
  thirdPartyFlag: 0,
  thirdPartyId: null,
  thirdPartyOrg: null
});

const showDrawer = () => {
  drawerVisible.value = true;
  selectRoleList().then(res => {
    roleList.value = res
  }).finally(() => {
  })
};

const handleCancel = () => {
  drawerVisible.value = false;
  Object.keys(formState).forEach(key => {
    if (Array.isArray(formState[key])) {
      formState[key] = [];
    } else {
      formState[key] = '';
    }
  });
};

const handleEditCancel = () => {
  editDrawerVisible.value = false;
  Object.keys(formState).forEach(key => {
    if (Array.isArray(formState[key])) {
      formState[key] = [];
    } else {
      formState[key] = '';
    }
  });
};

const handleSubmit = async () => {
  try {
    const res = await createUser(formState);
    message.success('新增用户成功');
    drawerVisible.value = false;
    Modal.info({
      title: '账号信息',
      content: `账号: ${res.account}\n密码: ${res.password}`,
      okText: '复制',
      onOk: () => {
        copyToClipboard(`账号: ${res.account}\n密码: ${res.password}`);
        message.success('已复制到剪贴板');
      }
    });
    fetchData();
  } catch (error) {
    console.error('新增用户失败:', error);
    message.error('新增用户失败');
  }
};

const handleEditSubmit = async () => {
  try {
    const res = await updateSysUserInfo(formState.value);
    message.success('编辑用户成功');
    editDrawerVisible.value = false;
    fetchData();
  } catch (error) {
    console.error('编辑用户失败:', error);
    message.error('编辑用户失败');
  }
}

const roleList = ref([]);

const handleEdit = async (record) => {
  // 查询用户详情并填充表单
  if (record) {
    const res = await searchSysUserInfoById(record.id)
    if (res) {
      formState.value = res;
      formState.value.account=res.username
      formState.value.email=res.userEmail
      formState.value.provinceName=res.province
      formState.value.cityName=res.city
      console.log("res===>",res)
      console.log("formState===>",formState.value)
      editDrawerVisible.value = true;
    }
    
  }
  selectRoleList().then(res => {
    roleList.value = res
  }).finally(() => {
  })
};

const handleStatusChange = async (id, checked) => {
  try {
    statusLoadingId.value = id;
    await updateUserStatus({
      ids: [id],
      status: checked ? 0 : 1
    });
    message.success(checked ? '已启用用户' : '已禁用用户');
    fetchData();
  } catch (error) {
    console.error('状态更新失败:', error);
    message.error('状态更新失败');
  } finally {
    statusLoadingId.value = null;
  }
};

const handleDelete = (record) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 ${record.realName} 吗?`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        // 这里需要添加删除API调用
        message.success('删除成功');
        fetchData();
      } catch (error) {
        console.error('删除失败:', error);
        message.error('删除失败');
      }
    }
  });
};

const copyToClipboard = (text) => {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
};

const dataSource = ref([]);
const loading = ref(false);
const statusLoadingId = ref(null);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.current || 1,
      pageSize: pagination.pageSize || 10,
      ...searchForm,
    };
    const res = await getUsers(params);
    dataSource.value = res.entity.map(item => ({
      id: item.id || '',
      realName: item.realName || '',
      phone: item.phone || '',
      userEmail: item.userEmail || '',
      province: item.province || '',
      city: item.city || '',
      gender: item.gender || 0,
      registerTime: item.registerTime || '',
      userStatus: item.userStatus || 0
    }));
    pagination.total = res.count;
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

const resetSearch = () => {
  Object.assign(searchForm, {
    username: '',
    gender: '',
    userStatus: '',
  });
  handleSearch();
};

const handleTableChange = (paginationInfo, filters, sorter) => {
  if (paginationInfo && paginationInfo.current && paginationInfo.pageSize) {
    pagination.current = Number(paginationInfo.current) || 1;
    pagination.pageSize = Number(paginationInfo.pageSize) || 10;
    // 重置当前页为1当切换每页条数时
    if (filters && Object.keys(filters).length === 0 && !sorter) {
      pagination.current = 1;
    }
  }
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.user-list-container {
  
  background: #fff;
}

.search-card {
  margin-bottom: 0;
}

.divider {
  height: 16px;
  background: #f0f2f5;
}

.table-card {
  margin-top: 0;
  height: calc(100vh - 320px - 64px); /* 减去分页高度 */
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.ant-card-body) {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.ant-table) {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  position: relative;
  margin-top: 16px;
  text-align: right;
  padding-right: 24px;
}


</style>